package com.ruoyi.washer.common;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.washer.mapper.XwDeviceMapper;
import com.ruoyi.washer.mapper.XwProductMapper;
import com.ruoyi.washer.mapper.XwPurchaseOrderMapper;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

@Service
public class PaymentDivideServiceImpl {
    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.appsecret}")
    private String secret;

    @Value("${wx.mch_id}")
    private String mchId;

    @Value("${wx.key_v2}")
    private String key_v2;

    @Value("${wx.key_v3}")
    private String key_v3;

    @Value("${wx.notify_url}")
    private String notify_url;

    @Value("${wx.refund_notify_url}")
    private String refund_notify_url;

    @Value("${wx.private_key}")
    private String private_key;

    @Value("${wx.mch_serial_no}")
    private String mch_serial_no;

    private static final Logger logger = LoggerFactory.getLogger(PaymentDivideServiceImpl.class);



    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private XwDeviceMapper xwDeviceMapper;

    @Autowired
    private XwProductMapper xwProductMapper;

    @Autowired
    private XwPurchaseOrderMapper xwPurchaseOrderMapper;

    /*分账请求*/
    public String createDivideOrder(String outTradeNo, String transactionId, JSONArray receivers,String description) {
        try {
            PrivateKey merchantPrivateKey = PemUtil
                    .loadPrivateKey(new ByteArrayInputStream(private_key.getBytes("utf-8")));
            // 获取证书管理器实例
            CertificatesManager certificatesManager = CertificatesManager.getInstance();
            // 向证书管理器增加需要自动更新平台证书的商户信息
            certificatesManager.putMerchant(mchId,
                    new WechatPay2Credentials(mchId,
                            new PrivateKeySigner(mch_serial_no, merchantPrivateKey)),
                    key_v3.getBytes(StandardCharsets.UTF_8));

            CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                    .withMerchant(mchId, mch_serial_no, merchantPrivateKey)
                    .withValidator(new WechatPay2Validator(certificatesManager.getVerifier(mchId)))
                    .build();
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/profitsharing/orders");
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.addHeader("Wechatpay-Serial", mch_serial_no);
            JSONArray jsonArray=new JSONArray();
            for(int i=0;i<receivers.size();i++){
                String cashoutType=receivers.getJSONObject(i).getString("cashoutType");
                if(cashoutType.equals("1")){
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("type","PERSONAL_OPENID");
                    jsonObject.put("account",receivers.getJSONObject(i).getString("account"));
                    jsonObject.put("amount",receivers.getJSONObject(i).getIntValue("getMoney"));
                    jsonObject.put("description",description);
                    jsonArray.add(jsonObject);
                }else{
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("type","MERCHANT_ID");
                    jsonObject.put("account",receivers.getJSONObject(i).getString("account"));
                    jsonObject.put("amount",receivers.getJSONObject(i).getIntValue("getMoney"));
                    jsonObject.put("name",receivers.getJSONObject(i).getString("accountName"));
                    jsonObject.put("description",description);
                    jsonArray.add(jsonObject);
                }
            }
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("appid", appid);
            jsonObject.put("transaction_id", transactionId);
            jsonObject.put("out_order_no", outTradeNo);
            jsonObject.put("receivers", jsonArray);
            jsonObject.put("unfreeze_unsplit", true);
            httpPost.setEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            System.out.println(jsonObject.toString());
            String bodyAsString = EntityUtils.toString(response.getEntity());
            //{"code":"INVALID_REQUEST","message":"分账对象重复"}
            System.out.println(bodyAsString);
            return bodyAsString;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    /*
        查询分账结果
         */
    public String queryDivideOrder(String outTradeNo) throws Exception{
        String bodyAsString="";
        try {
            PrivateKey merchantPrivateKey = PemUtil
                    .loadPrivateKey(new ByteArrayInputStream(private_key.getBytes("utf-8")));
            // 获取证书管理器实例
            CertificatesManager certificatesManager = CertificatesManager.getInstance();
            // 向证书管理器增加需要自动更新平台证书的商户信息
            certificatesManager.putMerchant(mchId,
                    new WechatPay2Credentials(mchId,
                            new PrivateKeySigner(mch_serial_no, merchantPrivateKey)),
                    key_v3.getBytes(StandardCharsets.UTF_8));
            CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                    .withMerchant(mchId, mch_serial_no, merchantPrivateKey)
                    .withValidator(new WechatPay2Validator(certificatesManager.getVerifier(mchId)))
                    .build();
            outTradeNo="17036705599741101122";
            String transactionId="4200002079202312288691877800";
            URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/profitsharing/orders/"+outTradeNo+"?transaction_id="+transactionId);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("Accept", "application/json");
            CloseableHttpResponse response = httpClient.execute(httpGet);
            bodyAsString = EntityUtils.toString(response.getEntity());
            System.out.println(bodyAsString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bodyAsString;
    }

    /*增加分账人*/
    public String addDividUser(String openId) {
        try {
            PrivateKey merchantPrivateKey = PemUtil
                    .loadPrivateKey(new ByteArrayInputStream(private_key.getBytes("utf-8")));
            // 获取证书管理器实例
            CertificatesManager certificatesManager = CertificatesManager.getInstance();
            // 向证书管理器增加需要自动更新平台证书的商户信息
            certificatesManager.putMerchant(mchId,
                    new WechatPay2Credentials(mchId,
                            new PrivateKeySigner(mch_serial_no, merchantPrivateKey)),
                    key_v3.getBytes(StandardCharsets.UTF_8));

            CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                    .withMerchant(mchId, mch_serial_no, merchantPrivateKey)
                    .withValidator(new WechatPay2Validator(certificatesManager.getVerifier(mchId)))
                    .build();
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/profitsharing/receivers/add");
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectMapper objectMapper = new ObjectMapper();

            ObjectNode rootNode = objectMapper.createObjectNode();
            rootNode.put("appid", appid)
                    .put("type", "PERSONAL_OPENID")
                    .put("account", openId)
                    .put("relation_type", "PARTNER");
            objectMapper.writeValue(bos, rootNode);
            httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String bodyAsString = EntityUtils.toString(response.getEntity());
            System.out.println(bodyAsString);
            return bodyAsString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*删除分账人*/
    public String deleteDividUser() {
        try {
            PrivateKey merchantPrivateKey = PemUtil
                    .loadPrivateKey(new ByteArrayInputStream(private_key.getBytes("utf-8")));
            // 获取证书管理器实例
            CertificatesManager certificatesManager = CertificatesManager.getInstance();
            // 向证书管理器增加需要自动更新平台证书的商户信息
            certificatesManager.putMerchant(mchId,
                    new WechatPay2Credentials(mchId,
                            new PrivateKeySigner(mch_serial_no, merchantPrivateKey)),
                    key_v3.getBytes(StandardCharsets.UTF_8));

            CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                    .withMerchant(mchId, mch_serial_no, merchantPrivateKey)
                    .withValidator(new WechatPay2Validator(certificatesManager.getVerifier(mchId)))
                    .build();
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/profitsharing/receivers/delete");
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectMapper objectMapper = new ObjectMapper();

            ObjectNode rootNode = objectMapper.createObjectNode();
            //String outRefundNo = stringToMD5("refund"+outTradeNo);
            rootNode.put("appid", appid)
                    .put("type", "PERSONAL_OPENID")
                    .put("account", "ofMKV6z5NOOQ14BBIZYwQdJofiWg");
            objectMapper.writeValue(bos, rootNode);
            httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String bodyAsString = EntityUtils.toString(response.getEntity());
            System.out.println(bodyAsString);
            return bodyAsString;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
